package com.firewolf.vue.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 作者：刘兴
 * 时间:19/3/6
 **/
public class CustomUserDetailsService implements UserDetailsService {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Map<String, Object> map = null;
        try {
            map = jdbcTemplate.queryForMap("select * from sys_user where name=?", username); //查询用户
        } catch (Exception e) {
            throw new UsernameNotFoundException("账号不存在....");
        }
        List<GrantedAuthority> authorityList = new ArrayList<>();

        String sql = "select p.perms from sys_permission p left join sys_role_permission  rp on rp.permssion_id =p.id left join sys_role r on rp.role_id=r.id left join sys_user_role ur on ur.role_id=r.id where ur.user_id=?";

        List<String> strings = jdbcTemplate.queryForList(sql, String.class,map.get("id"));
        System.out.println(strings);
        if (strings != null && strings.size() > 0)
            strings.stream().forEach(x -> authorityList.add(new SimpleGrantedAuthority(x)));

        User user = new User(map.get("name").toString(), map.get("password").toString(), authorityList);

        return user;
    }
}
